//
//  RecordViewController.m
//  KeleAppProject
//
//  Created by Cen Zhou on 2018/1/19.
//  Copyright © 2018年 Cen Zhou. All rights reserved.
//

#import "RecordViewController.h"
#import "VideoVC.h"
#import "KeleNavigationController.h"
#import <AliyunVideoSDK/AliyunVideoSDK.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "LinkVC.h"
@interface RecordViewController ()<AliyunVideoBaseDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic ,strong) UIImagePickerController * imagePicker;
@property (nonatomic, strong) UIView *recordView;
@property (nonatomic, strong) UIView *photoView;
@property (nonatomic, strong) UIView *lianjieView;

@end

@implementation RecordViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    // 调取用户信息接口  要更新数据
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self loadSubviewsOnRecord];
}

- (void)loadSubviewsOnRecord{
    
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelButton setBackgroundImage:[UIImage imageNamed:@"icon_tc_guanbi"] forState:UIControlStateNormal];
    [[cancelButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(UIButton *x) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    [self.view addSubview:cancelButton];
    [cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-50*HEIGHT);
        make.width.height.mas_equalTo(44*WIDTH);
    }];
    // 录制
    UIView *recordView = [[UIView alloc]init];
    recordView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:recordView];
    self.recordView = recordView;
    [recordView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view.mas_bottom);
        make.height.mas_equalTo(66*HEIGHT);
    }];
    
    UIImageView *recordImageView = [[UIImageView alloc]init];
    recordImageView.image = [UIImage imageNamed:@"icon_luzhi"];
    recordImageView.contentMode = UIViewContentModeScaleAspectFit;
    [recordView addSubview:recordImageView];
    [recordImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(recordView);
        make.left.equalTo(recordView).offset(103*WIDTH);
        make.width.height.mas_equalTo(66*WIDTH);
    }];
    
    UILabel *recordTint = [[UILabel alloc]init];
    recordTint.text = @"录制";
    recordTint.textColor = KLColor_B6;
    recordTint.font = [UIFont fontWithName:@"PingFangSC-Medium" size:18*WIDTH];
    [recordView addSubview:recordTint];
    [recordTint mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(recordView);
        make.left.equalTo(recordImageView.mas_right).offset(30*WIDTH);
    }];
    
    
    


    
    // 相册
    UIView *photoView = [[UIView alloc]init];
    photoView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:photoView];
    self.photoView = photoView;
    [photoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view.mas_bottom);
        make.height.mas_equalTo(66*HEIGHT);
    }];
    
    UIImageView *photoImageView = [[UIImageView alloc]init];
    photoImageView.image = [UIImage imageNamed:@"icon_xiangce"];
    photoImageView.contentMode = UIViewContentModeScaleAspectFit;
    [photoView addSubview:photoImageView];
    [photoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(photoView);
        make.left.equalTo(photoView).offset(103*WIDTH);
        make.width.height.mas_equalTo(66*WIDTH);
    }];
    
    UILabel *photoTint = [[UILabel alloc]init];
    photoTint.text = @"相册";
    photoTint.textColor = KLColor_B6;
    photoTint.font = [UIFont fontWithName:@"PingFangSC-Medium" size:18*WIDTH];
    [photoView addSubview:photoTint];
    [photoTint mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(photoView);
        make.left.equalTo(photoImageView.mas_right).offset(30*WIDTH);
    }];
    
    // 链接
    UIView *addressLianView = [[UIView alloc]init];
    addressLianView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:addressLianView];
    self.lianjieView = addressLianView;
    
    [addressLianView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view.mas_bottom);
        make.height.mas_equalTo(66*HEIGHT);
    }];
    
    UIImageView *addressLianImageView = [[UIImageView alloc]init];
    addressLianImageView.image = [UIImage imageNamed:@"icon_lianjieshipin"];
    addressLianImageView.contentMode = UIViewContentModeScaleAspectFit;
    [addressLianView addSubview:addressLianImageView];
    [addressLianImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(addressLianView);
        make.left.equalTo(addressLianView).offset(103*WIDTH);
        make.width.height.mas_equalTo(66*WIDTH);
    }];
    
    UILabel *addressLianTint = [[UILabel alloc]init];
    addressLianTint.text = @"链接视频";
    addressLianTint.textColor = KLColor_B6;
    addressLianTint.font = [UIFont fontWithName:@"PingFangSC-Medium" size:18*WIDTH];
    [addressLianView addSubview:addressLianTint];
    [addressLianTint mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(addressLianView);
        make.left.equalTo(addressLianImageView.mas_right).offset(30*WIDTH);
    }];
    [self addTapView];
    [self springAnimationTextAction:CGPointMake(0, 179*HEIGHT) view:self.recordView];
    [self springAnimationTextAction:CGPointMake(0, 295*HEIGHT) view:self.photoView];
    [self springAnimationTextAction:CGPointMake(0, 411*HEIGHT) view:self.lianjieView];
}

- (void)springAnimationTextAction:(CGPoint)point view:(UIView *)view{
    if (@available(iOS 9.0, *)) {
    CASpringAnimation *springAnimation = [CASpringAnimation animationWithKeyPath:@"position.y"];
    
    springAnimation.fromValue = @(view.layer.position.y);
    springAnimation.toValue = @(point.y);
    
    
    //质量，影响图层运动时的弹簧惯性，质量越大，弹簧拉伸和压缩的幅度越大 Defaults to one
    springAnimation.mass = 10;
    //刚度系数(劲度系数/弹性系数)，刚度系数越大，形变产生的力就越大，运动越快 Defaults to 100
    springAnimation.stiffness = 100;
    //阻尼系数，阻止弹簧伸缩的系数，阻尼系数越大，停止越快 Defaults to 10
    springAnimation.damping = 45;
    //初始速率，动画视图的初始速度大小 Defaults to zero
    //速率为正数时，速度方向与运动方向一致，速率为负数时，速度方向与运动方向相反
    springAnimation.initialVelocity = 30;
    //估算时间 返回弹簧动画到停止时的估算时间，根据当前的动画参数估算
    NSLog(@"====%f",springAnimation.settlingDuration);
    springAnimation.duration = springAnimation.settlingDuration;
    
    //removedOnCompletion 默认为YES 为YES时，动画结束后，恢复到原来状态
    springAnimation.removedOnCompletion = NO;
    springAnimation.fillMode = kCAFillModeBoth;
    
    [view.layer addAnimation:springAnimation forKey:@"springAnimation"];
    }
}


// 因为改变了layer 所以暂时加覆盖解决
- (void)addTapView{
    UIView *recordView_tap = [[UIView alloc]init];
    recordView_tap.backgroundColor = [UIColor clearColor];
    recordView_tap.tag = 100;
    [self.view addSubview:recordView_tap];
    UITapGestureRecognizer *tapRecord = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClicks:)];
    [recordView_tap addGestureRecognizer:tapRecord];
    
    [recordView_tap mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(146*HEIGHT);
        make.height.mas_equalTo(66*HEIGHT);
    }];
    
    
    UIView *photoView_tap = [[UIView alloc]init];
    photoView_tap.backgroundColor = [UIColor clearColor];
    
    photoView_tap.tag = 101;
    [self.view addSubview:photoView_tap];
    UITapGestureRecognizer *tapPhoto = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClicks:)];
    [photoView_tap addGestureRecognizer:tapPhoto];
    [photoView_tap mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(262*HEIGHT);
        make.height.mas_equalTo(66*HEIGHT);
    }];
    
    
    UIView *addressLianView_tap = [[UIView alloc]init];
    addressLianView_tap.backgroundColor = [UIColor clearColor];
    addressLianView_tap.tag = 102;
    [self.view addSubview:addressLianView_tap];
    UITapGestureRecognizer *tapLian = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClicks:)];
    [addressLianView_tap addGestureRecognizer:tapLian];
    [addressLianView_tap mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(378*HEIGHT);
        make.height.mas_equalTo(66*HEIGHT);
    }];
}

- (void)tapClicks:(UITapGestureRecognizer *)tap{
    
    if (tap.view.tag == 100) {
       
        [self setupSDKBaseVersionUI];
        AliyunVideoRecordParam *param = [AliyunVideoRecordParam recordConfigWithVideoRatio:AliyunVideoVideoRatio3To4 videoSize:AliyunVideoVideoSize540P position:AliyunCameraPositionFront trochMode:AliyunCameraTorchModeOff beautifyStatus:YES beautifyValue:100 outputPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/record_save.mp4"] minDuration:2 maxDuration:30 videoQuality:AliyunVideoQualityHight encodeMode:AliyunVideoEncodeModeSoftH264 fps:10 gop:20];
        
        UIViewController *recordViewController = [[AliyunVideoBase shared] createRecordViewControllerWithRecordParam:param];
        [AliyunVideoBase shared].delegate = (id)self;
        [self.navigationController pushViewController:recordViewController animated:YES];
    }else if (tap.view.tag == 101){  // 相册
        [self addImageFromCameraOrFromAlbum:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
        
    }else if (tap.view.tag == 102){
        LinkVC *linkVc = [[LinkVC alloc]init];
        [self.navigationController pushViewController:linkVc animated:YES];
    }
    
}


#pragma mark - ----录制
- (void)setupSDKBaseVersionUI {
    
    AliyunVideoUIConfig *config = [[AliyunVideoUIConfig alloc] init];
    
    config.backgroundColor = [UIColor whiteColor];
    config.timelineBackgroundCollor = [UIColor whiteColor];
    config.timelineDeleteColor = [UIColor whiteColor];
    config.timelineTintColor = KLColor_A1 ;
    config.durationLabelTextColor = KLColor_B2;
    config.cutTopLineColor = [UIColor redColor];
    config.cutBottomLineColor = [UIColor redColor];
    config.noneFilterText = @"无滤镜";
    config.hiddenDurationLabel = NO;
    config.hiddenFlashButton = NO;
    config.hiddenBeautyButton = NO;
    config.hiddenCameraButton = NO;
    config.hiddenImportButton = YES;
    config.hiddenDeleteButton = NO;
    config.hiddenFinishButton = NO;
    config.recordOnePart = NO;
    config.filterArray = @[@"炽黄",@"粉桃",@"海蓝",@"红润",@"灰白",@"经典",@"麦茶",@"浓烈",@"柔柔",@"闪耀",@"鲜果",@"雪梨",@"阳光",@"优雅",@"朝阳",@"波普",@"光圈",@"海盐",@"黑白",@"胶片",@"焦黄",@"蓝调",@"迷糊",@"思念",@"素描",@"鱼眼",@"马赛克",@"模糊"];
    config.imageBundleName = @"vedio";
    config.filterBundleName = @"FilterResource";
    config.recordType = AliyunVideoRecordTypeCombination;
    config.showCameraButton = YES;
    [[AliyunVideoBase shared] registerWithAliyunIConfig:config];
    
    
   
}
#pragma mark --- 代理方法
-(void)videoBaseRecordVideoExit {
    NSLog(@"退出录制");
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)videoBase:(AliyunVideoBase *)base recordCompeleteWithRecordViewController:(UIViewController *)recordVC videoPath:(NSString *)videoPath {
    NSLog(@"录制完成  %@", videoPath);
    VideoVC *videoVc = [[VideoVC alloc]init];
    [self.navigationController pushViewController:videoVc animated:YES];
    // 写入相册
//    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
//    [library writeVideoAtPathToSavedPhotosAlbum:[NSURL fileURLWithPath:videoPath]
//                                completionBlock:^(NSURL *assetURL, NSError *error) {
//
//                                    dispatch_async(dispatch_get_main_queue(), ^{
//                                        [recordVC.navigationController popViewControllerAnimated:YES];
//                                    });
//                                }];
}



//添加图片或者拍照
- (void)addImageFromCameraOrFromAlbum:(UIImagePickerControllerSourceType)type{
    // 因为是controller 所以不能用self
    _imagePicker = [[UIImagePickerController alloc] init];
    _imagePicker.delegate = self;
    _imagePicker.sourceType = type;
    _imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    _imagePicker.allowsEditing = YES;
    _imagePicker.navigationBar.barTintColor = [UIColor whiteColor];
    _imagePicker.navigationBar.tintColor = [UIColor whiteColor];
    [self presentViewController:_imagePicker animated:YES completion:nil];
}
//得到拍下来的照片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    // 得到照片信息
    // UIImage *images=[info objectForKey:UIImagePickerControllerOriginalImage];
    NSString* mediaType=[info objectForKey:UIImagePickerControllerMediaType];
    if([mediaType isEqualToString:(NSString *)kUTTypeMovie]){//如果是录制视频
        NSLog(@"video...");
        NSURL *url=[info objectForKey:UIImagePickerControllerMediaURL];//视频路径
//        NSString *urlStr=[url path];
//        if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(urlStr)) {
//            //保存视频到相簿，注意也可以使用ALAssetsLibrary来保存
//            UISaveVideoAtPathToSavedPhotosAlbum(urlStr, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);//保存视频到相簿
//        }
        
    }

    [_imagePicker dismissViewControllerAnimated:YES completion:nil];
    
    VideoVC *videoVc = [[VideoVC alloc]init];
    [self.navigationController pushViewController:videoVc animated:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
